package com.admin.filter;

import com.admin.entity.Admin;
import com.admin.service.ServiceAdmin;
import com.uni.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * --------------project-------------
 *
 * @Author Unirithe  - Mr.Chao
 * - CSDN:
 * https://blog.csdn.net/Unirithe
 * - GitHub:
 * https://github.com/unirithe
 * @create 2021/12/29 13:24
 * ------------------------------------------
 */
@WebFilter(filterName = "AdminLoginFilter", urlPatterns = {"/admin.jsp"})
public class AdminLoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        HttpSession session = request.getSession();
        /* 检验当前用户是否为管理员 */
        User user = (User) session.getAttribute("userInfo");
        System.out.println("123123123213123");
        if(user == null){
            response.sendRedirect("login.jsp");
        } else {
            Admin admin = ServiceAdmin.admin.selectById(user.getId());
            if(admin == null) {
                response.sendRedirect("index.jsp");
            }
            else
                filterChain.doFilter(req, resp);
        }
    }
}
